package com.zycfc.zsf.boot.job.service;

import com.google.common.util.concurrent.*;
import java.util.concurrent.*;
import com.zycfc.zsf.boot.job.common.*;
import org.springframework.util.*;
import java.util.*;
import org.slf4j.*;

public class ZsfJobShardCacheManager
{
    private static final Logger log;
    private ScheduledExecutorService executorService;
    
    public ZsfJobShardCacheManager() {
        this.executorService = new ScheduledThreadPoolExecutor(1, new ThreadFactoryBuilder().setNameFormat("flushZsfJobShardCache-pool-%d").build(), new ThreadPoolExecutor.AbortPolicy());
    }
    
    public void init() {
        this.executorService.scheduleWithFixedDelay(this::flushShardCache, 20L, 120L, TimeUnit.SECONDS);
    }
    
    public void close() {
        if (this.executorService != null) {
            this.executorService.shutdownNow();
        }
    }
    
    private void flushShardCache() {
        try {
            final Map<String, List<Integer>> latestPartitions = ShardStorage.queryPartitions();
            if (CollectionUtils.isEmpty((Map)latestPartitions)) {
                ZsfJobShardCacheManager.log.debug("zsfJob: can not query db partitions info, flush shard cache will be run at the next time");
                return;
            }
            if (!CollectionUtils.isEmpty((Map)latestPartitions) && latestPartitions.equals(ShardStorage.getPartition())) {
                ZsfJobShardCacheManager.log.debug("zsfJob: partitions info not change, no need flush shard cache");
                return;
            }
            this.doFlushShardCache(latestPartitions);
        }
        catch (Throwable e) {
            ZsfJobShardCacheManager.log.error("zsfJob: flush shard cache happen an exception, error is [{}]", (Object)e.getMessage(), (Object)e);
        }
    }
    
    private void doFlushShardCache(final Map<String, List<Integer>> latestPartitions) {
        synchronized (ShardStorage.class) {
            ShardStorage.getPartition().clear();
            ShardStorage.setPartitions(latestPartitions);
            ShardStorage.getJobPartitions().clear();
            ZsfJobShardCacheManager.log.debug("zsfJob: flush shard cache success!");
        }
    }
    
    static {
        log = LoggerFactory.getLogger((Class)ZsfJobShardCacheManager.class);
    }
}
